import { SvgIcon } from '@/components/icon';
import { useRoleManage, useRoleManageActions } from '@/store/roleManageStore';
import { useUserInfo } from '@/store/userStore';
import { Role } from '@/types/role';
import { getBackground } from '@/utils/tree';
import {
  CrownFilled,
  CrownTwoTone,
  DownOutlined,
  ReadOutlined,
  RightOutlined,
  SearchOutlined,
  UserAddOutlined,
  UserDeleteOutlined,
} from '@ant-design/icons';
import { Input, Select, Skeleton, Tooltip } from 'antd';
import { useEffect, useState } from 'react';
import cloneDeep from 'lodash/cloneDeep';
import userService from '@/api/services/userService';
import usePermission from '@/hooks/event/usePermission';

interface Props {
  loading: boolean;
  datas: Role[];
  selectedItem: Role | undefined;
  onItemClicked?: (item: Role) => void;
  version?: string;
}
type ExpandedItems = Record<string, boolean>;

const RoleList = ({ loading, datas, selectedItem, onItemClicked, version }: Props) => {
  const [searchValue, setSearchValue] = useState('');

  const actions = useRoleManageActions();
  const roleManage = useRoleManage();

  const [roleList, setRoleList] = useState([]);
  const [selectedRole, setSelectedRole] = useState('');
  const [filterRole, setFilterRole] = useState<Role[]>([]);
  const { role: userRole } = useUserInfo();

  const { isAdmin } = usePermission();

  const toggleExpand = (itemId: string) => {
    const expands = {
      ...roleManage.expandItems,
      [itemId]: !roleManage.expandItems[itemId],
    };
    actions.setExpandItems(expands);
  };

  const updateSubAdminRecursively: Role[] = (nodes: Role[], id: string, flag: boolean) => {
    return nodes.map((node: Role) => {
      if (node.id === id) {
        return { ...node, is_sub_admin: flag };
      }
      if (node.children && node.children.length > 0) {
        return {
          ...node,
          children: updateSubAdminRecursively(node.children, id, flag),
        };
      }
      return node;
    });
  };

  const datasetIconRender = (item: Role, index: number) => {
    const selected = selectedItem?.id == item.id;
    return (
      <div key={item.id}>
        <div
          className={`flex cursor-pointer items-center self-center rounded-lg p-2 hover:bg-white ${selected ? 'bg-Gainsboro hover:bg-Gainsboro hover:opacity-80' : ''
            }`}
          style={{ fontSize: '20' }}
          onClick={() => {
            onItemClicked && onItemClicked(item);
          }}
        >
          {item.children && item.children.length > 0 ? (
            <div
              className="ml-2 mr-2 w-4 cursor-pointer"
              onClick={(e) => {
                e.stopPropagation();
                toggleExpand(item.id);
              }}
            >
              {roleManage.expandItems[item.id] ? <DownOutlined /> : <RightOutlined />}
            </div>
          ) : (
            <div
              className="ml-2 mr-2 w-4 cursor-pointer"
              onClick={(e) => {
                e.stopPropagation();
                toggleExpand(item.id);
              }}
            ></div>
          )}
          <SvgIcon
            color={selected ? '#6D35FF' : '#33ADFF'}
            className="mb-1 ml-1 mr-1 mt-1"
            icon="icon-park-solid--people"
            size={28}
          />
          <div
            className="ml-2 items-center self-center truncate"
            style={{ color: selected ? '#6D35FF' : '#000' }}
          >
            {item.name}
          </div>
          <div className="flex-grow"></div>
          {item?.code != 'admin' && (
            <div className="pl-2 pr-2">
              {item?.permissions?.filter((i: any) => i.action === 'admin')?.length > 0 && (
                <>
                  <Tooltip title={'该角色下有可管理的资源'}>
                    <ReadOutlined style={{ color: selected ? '#6D35FF' : '#ce33e6' }} />
                  </Tooltip>
                </>
              )}
              {/* {
                isAdmin && userRole?.id != item?.id && item?.is_sub_admin &&
                <Tooltip title={"取消管理员"}>
                  <CrownFilled style={{ color: '#ffc82c', paddingLeft: '5px' }}
                    onClick={async (e) => {
                      e.preventDefault()
                      e.stopPropagation();
                      userService.updateRoleType(item?.id).then(() => {
                        const updatedItems = updateSubAdminRecursively(filterRole, item?.id, false)
                        setFilterRole(updatedItems)
                      })
                    }} />
                </Tooltip>
              }
              {
                isAdmin && userRole?.id != item?.id && !item?.is_sub_admin &&
                <Tooltip title={"设置管理员"}>
                  <CrownFilled style={{ color: '#C4CDD5', paddingLeft: '5px' }}
                    onClick={async (e) => {
                      e.preventDefault()
                      e.stopPropagation();
                      userService.updateRoleType(item?.id).then(() => {
                        const updatedItems = updateSubAdminRecursively(filterRole, item?.id, true)
                        setFilterRole(updatedItems)
                      })
                    }} />
                </Tooltip>
              } */}
            </div>
          )}
        </div>
        {item.children && item.children.length > 0 && roleManage.expandItems[item.id] && (
          <div className="ml-8">
            {item.children
              .filter((item) => item.name.includes(searchValue))
              .map((child, childIndex) => datasetIconRender(child, childIndex))}
          </div>
        )}
      </div>
    );
  };

  // useEffect(() => {
  //   userService.getRolePermissions().then((res) => {
  //     const newRoleList = res
  //       .filter((i) => userRole?.code.includes(i?.code) || userRole?.code == i?.code)
  //       .map((item: Role) => ({
  //         value: item.code,
  //         label: item.name,
  //       }))
  //       .filter((item, index, self) => {
  //         return self.findIndex((i) => i.value === item.value) === index;
  //       });
  //     setRoleList(newRoleList);

  //     if (res?.length > 0) {
  //       if (roleManage?.selectedRole) {
  //         const roleExists = newRoleList.some(
  //           (item) => item.value === roleManage?.selectedRole?.code,
  //         );
  //         if (roleExists) {
  //           setSelectedRole(roleManage?.selectedRole?.code);
  //         } else {
  //           setSelectedRole(newRoleList?.[0]?.value);
  //         }
  //       } else {
  //         setSelectedRole(newRoleList?.[0]?.value);
  //       }
  //       res?.length == 1 && setFilterRole(cloneDeep(datas));
  //     }
  //   });
  // }, []);

  useEffect(() => {
    if (roleList?.length > 1) {
      console.log(datas);
      const users = datas.filter((item) => item?.code == selectedRole);
      let newFilterRole;
      if (users[0]?.code === 'admin') {
        newFilterRole = datas.filter(
          (item) => item?.is_built_in === true || item?.code === selectedRole,
        );
      } else {
        newFilterRole = [users[0]];
      }
      const uniqueFilterRole = [];
      const codeSet = new Set();
      newFilterRole.forEach((item) => {
        if (item?.code && !codeSet.has(item.code)) {
          uniqueFilterRole.push(item);
          codeSet.add(item.code);
        }
      });
      setFilterRole(uniqueFilterRole);
      onItemClicked && onItemClicked(users[0]);
    } else {
      if (roleManage?.selectedRole) {
        onItemClicked && onItemClicked(roleManage?.selectedRole);
      } else {
        const users = datas.filter((item) => item?.code == selectedRole);
        onItemClicked && onItemClicked(users[0]);
      }
      setFilterRole(cloneDeep(datas));
    }
  }, [selectedRole, datas]);

  return (
    <>
      <div className="flex h-full flex-col rounded-lg p-2">
        <Input
          style={{ border: 'none', background: '#F5F7FB' }}
          placeholder="搜索..."
          className="mb-2 text-sm"
          value={searchValue}
          prefix={<SearchOutlined style={{ color: '#C9CEE2', marginRight: '10px' }} />}
          onChange={(e) => {
            setSearchValue(e.target.value);
          }}
        />
        {loading && (
          <div>
            <Skeleton paragraph={{ rows: 24 }} />
          </div>
        )}
        {!loading && (
          <div className="h-full flex-1 overflow-y-auto overflow-x-hidden rounded-lg bg-[#F5F7FB]">
            {/* {!version && roleList?.length > 0 && (
              <div className="flex items-center p-2">
                <div className="w-20">当前角色</div>

                <Select
                  // defaultValue=""
                  value={selectedRole}
                  style={{ width: '100%' }}
                  onChange={(value) => {
                    console.log(value);
                    setSelectedRole(value);
                  }}
                  options={roleList}
                />
              </div>
            )} */}
            {filterRole
              .filter(
                (item) =>
                  item.name.includes(searchValue) ||
                  item.children?.filter((c) => c.name.includes(searchValue)).length > 0,
              )
              .map((item, index) => {
                return datasetIconRender(item, index);
              })}
          </div>
        )}
      </div>
    </>
  );
};

export default RoleList;
